package evs.activation;

import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.net.URI;
import java.util.Vector;

import evs.brp.ClientRequestHandler;
import evs.brp.RemotingErrorException;

public class Requestor extends evs.brp.Requestor {

	@Override
	protected Object invoke (String clazz, String methodName, 
			Vector<Class> argumentclazzes, Vector<String> argumentNames, Vector<Object> arguments, 
			Class returnClazz) throws RemotingErrorException {
		
		/*
		 * connect to remote server and get output object stream
		 */
		ObjectOutput objectOutput = clientRequestHandler.connect();
		
		/*
		 * use object output stream to marshall remote call
		 */
		Message message = new Message(clazz, methodName,
				argumentclazzes, argumentNames, arguments,
				returnClazz);
		
		/**
		 * set object instance name (whichis part of uri)
		 */
		message.setObjectInstanceName(this.clientRequestHandler.getUri().getPath());

		/**
		 * requestor hash code is currently used as client ID
		 * TODO: think about: may thsi cause problems?
		 */
		message.setClientId(new Integer(this.hashCode()).toString());
		
		
		Marshaller.marshall(objectOutput, message);
		
		/*
		 * send remote call and get input object stream
		 */
		ObjectInput objectInput = clientRequestHandler.send();
		
		/*
		 * use input object stream to demarshall return value
		 */
		Message returnMessage = Marshaller.demarshall(objectInput);
		
		/**
		 * check if message contains an exception
		 */
		if(returnMessage.getException() != null) {
			log.info("found marshalled remote exception, will throw it now");
			throw returnMessage.getException();
		}
		
		return returnMessage.getReturnValue();
	}
	
}
